import {openDB, addCreateTime,addUpdateTime} from "../useDB.js";

/**
 *声明数据表objectStore和索引tableIndex
 */
let params = {
    objectStore: 'card',
    tableIndex: ['id','price', 'time']
}


// /**
//  * 通过索引和游标分页查询记录
//  * @param {object} db 数据库实例
//  * @param {string} storeName 仓库名称
//  * @param {string} indexName 索引名称
//  * @param {number} indexValue 索引值
//  * @param {number} page 页码
//  * @param {number} pageSize 查询条数
//  */
export function CardSelectData(
    page,
    pageSize
) {
    return new Promise((resolve, reject) => {
        openDB(params).then(db => {

            let list = [];
            let counter = 0; // 计数器
            let advanced = true; // 是否跳过多少条查询
            var store = db.transaction(params.objectStore, "readwrite").objectStore(params.objectStore); // 仓库对象
            var request = store
                // .index(indexName) // 索引对象
                // .openCursor(IDBKeyRange.upperBound(indexValue)); // 指针对象
                .openCursor(); // 指针对象
            request.onsuccess = function (e) {
                var cursor = e.target.result;
                if (page > 1 && advanced) {
                    advanced = false;
                    cursor.advance((page - 1) * pageSize); // 跳过多少条
                    return;
                }
                if (cursor) {
                    // 必须要检查
                    list.push(cursor.value);
                    counter++;
                    if (counter < pageSize) {
                        cursor.continue(); // 遍历了存储对象中的所有内容
                    } else {
                        cursor = null;
                        resolve(list)
                        console.log("分页查询结果", list);
                    }
                } else {
                    resolve(list)
                    console.log("分页查询结果", list);
                }
            };
            request.onerror = function (e) {
                reject(e)
                console.log("分页查询失败");
            };


        })




    })

}



/**
 * 新增数据
 * @param {string} data 数据
 */
export function CardAddData(data) {
    return new Promise((resolve, reject) => {
        openDB(params).then(db => {
            data = addCreateTime(data)
            const request = db
                .transaction([params.objectStore], "readwrite") // 事务对象 指定表格名称和操作模式（"只读"或"读写"）
                .objectStore(params.objectStore) // 仓库对象
                .add(data);

            request.onsuccess = function (event) {
                resolve(event)
                console.log("【CardAddData】数据写入成功", {id: event.target.result, ...data});
                db.close()
            };
            request.onerror = function (event) {
                reject(event)
                console.log("【CardAddData】数据写入失败", event);
                db.close()
            };
        })
    })
}

/**
 * 更新数据 更新特定的字段
 * @param {object} data 数据
 */
export function CardUpdateData(data) {
    return new Promise((resolve, reject) => {
        openDB(params).then(db => {
            data = addUpdateTime(data)
            const transaction = db.transaction([params.objectStore], 'readwrite');
            const objectStore = transaction.objectStore(params.objectStore);
            const getRequest = objectStore.get(data.id);

            getRequest.onsuccess = function (event) {
                const originalData = getRequest.result;
                // 更新特定的字段
                for(let v in data){
                    originalData[v] = data[v]
                }
                const updateRequest = objectStore.put(originalData);
                updateRequest.onsuccess = function (res) {
                    resolve(res)
                    console.log('【CardUpdateData】更新数据成功',originalData)
                    db.close()
                };
                updateRequest.onerror = function (e) {
                    reject(e)
                    console.log('【CardUpdateData】更新数据失败')
                    db.close()
                };
            };
        })
    })
}

/**
 * 通过主键删除数据
 * @param {number} id 主键值
 */
export function CardDeleteData(id) {
    return new Promise((resolve, reject) => {
        openDB(params).then(db => {
            const request = db
                .transaction([params.objectStore], "readwrite")
                .objectStore(params.objectStore)
                .delete(id);

            request.onsuccess = function (res) {
                resolve(res)
                console.log(res)
                console.log('数据删除成功',id)
            };

            request.onerror = function (e) {
                reject(e)
                console.log('数据删除失败')
            };
        })

    })

}
